import datetime
import os
import json

from config import interpreter
from models import Toolkit
from views.utils.toolkit_service import python_insert_args, shell_insert_args
from views.utils.log import logger

logger.debug(os.getcwd())
script_header = """
import os

PROJECT_PATH = '/home/Tang/work/a-ops/'
UTILS_FILE = f"{os.path.join(PROJECT_PATH, 'views/utils/template.py')}"

with open(UTILS_FILE, 'r') as file:
    code = compile(file.read(), UTILS_FILE, 'exec')
    exec(code)
"""


def generate_script(db_tool: Toolkit, tool, file = True):
    """本地执行脚本"""
    if not db_tool.content:
        return False

    new_args = {x['id']: x.get('value','') for x in tool.args}
    run_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    run_name = f"{db_tool.name}_{run_id}"
    cache_dir = os.sep.join([os.getcwd(), 'cache', 'toolkit'])

    if not os.path.isdir(cache_dir):
        os.makedirs(cache_dir)

    if db_args := db_tool.args:
        db_args = json.loads(db_args)

        # 覆盖默认参数
        if tool.content:
            db_tool.content = tool.content
        if new_args:
            for db_arg in db_args:
                if db_arg['id'] not in new_args:
                    continue
                db_arg['value'] = new_args[db_arg['id']]
    content_args = ''
    if db_args:
        if db_tool.type == 1:
            content_args = shell_insert_args(db_args)
        elif db_tool.type == 2:
            content_args = python_insert_args(db_args)

    content_header = """"""
    content_body = ''
    if db_tool.type == 1:
        content_body = f"{content_args}\n{db_tool.content}"
        content_body = content_body.replace('\r\n', '\n')
    elif db_tool.type == 2:
        content_body = f"{content_header}\n{content_args}\n{db_tool.content}"

    interpreter_enum = {
        1: (run_name + '.sh', '/usr/bin/bash'),
        2: (run_name + '.py', interpreter),
    }
    script = f"{cache_dir}{os.sep}{interpreter_enum[db_tool.type][0]}"
    if file:
        with open(script, 'w+', encoding='utf-8') as f:
            f.write(content_body)

        command = [interpreter_enum[db_tool.type][1], script]
        return command
    else:
        return interpreter_enum[db_tool.type][1], content_body


if __name__ == '__main__':
    print(script_start('cache/flow/64ae9607ecc3064f90d8afa8-1705283780723949645.py'))
